package com.frame.service.impl;

import java.io.Serializable;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;

import com.frame.action.form.Form;

public class service implements Serializable {
	
	protected <T> T formToEntity(Class<T> beanClass, Form form){
		try {
			T bean = beanClass.newInstance();
			return formToEntity(bean, form);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@SuppressWarnings("unchecked")
	protected <T> T formToEntity(T entity, Form form){
		try {
			Map formMap = BeanUtils.describe(form);
			Iterator<String> properties = formMap.keySet().iterator();
			while(properties.hasNext()){
				String prop = properties.next();
				Object o =  BeanUtils.getProperty(form, prop);
				//���ﲻʹ��copyProperties������ԭ���Ƕ���null���͵����������ת�䣬
				//��IntegerΪnullʱ������Ϊ0,��PropertyUtils�ֲ�֧������ת��
				if(o == null || !PropertyUtils.isWriteable(entity, prop))
					continue;
				BeanUtils.copyProperty(entity, prop, o);
			}
			return entity;
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return null;
	}
}
